@extends('layout.master')

@section('content-header')
    <h1>Pencarian Lokasi</h1>
    <ol class="breadcrumb">
        <li><a href="/"><i class="fa fa-dashboard"></i> Dashboard</a></li>
        <li><a href="{{ URL::route('lokasis') }}"><i class="fa fa-map-marker"></i> Lokasi</a></li>
        <li class="active"><i class="fa fa-search"></i> Pencarian</li>
    </ol>
@stop

@section('content')

<!-- Modal -->
<div class="modal fade modal-wide" id="detail-lokasi-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">Detail Lokasi</h4>
            </div>

            <div class="modal-body">

            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-sm btn-danger" data-dismiss="modal"><i class="fa fa-times"></i> Tutup</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<div class="row">
    <div class="col-xs-12">
        <div class="box">
            <div class="box-header">

            </div>
            <div class="box-body">
                <div class="row">
                    <div id="box-filter" class="col-md-12 nopadding">
                        <form id="frmFilter">
                        <ul class="list-unstyled clearfix">
                            <li class="col-xs-3">
                                Nama Lokasi
                                <input type="text" id="fl_nama_lokasi" name="fl_nama_lokasi" class="form-control input-sm" placeholder="Nama Lokasi"/>
                            </li>
                            <li class="col-xs-2">
                                Tipe Lokasi
                                <select id="fl_tipe" name="fl_tipe" class="form-control input-sm">
                                    <option value="">Semua Tipe</option>
                                    @foreach($tipes as $tipe)
                                    <option value="{{ $tipe->id }}">{{ $tipe->nama; }}</option>
                                    @endforeach
                                </select>
                            </li>
                        </ul>
                        <ul class="list-unstyled clearfix">
                            <li class="col-xs-3">
                                <div class="input-group">
                                    <div class="input-group-addon"><input type="checkbox" id="fl_kipem_akan_habis" name="fl_kipem_akan_habis" class="input-sm"></div>
                                    <label for="fl_kipem_akan_habis" class="form-control label-filter input-sm">Kipem akan habis</label>
                                </div>
                            </li>
                            <li class="col-xs-3">
                                <div class="input-group">
                                    <div class="input-group-addon"><input type="checkbox" id="fl_kipem_habis" name="fl_kipem_habis" class="input-sm"></div>
                                    <label for="fl_kipem_habis" class="form-control label-filter input-sm">Kipem habis</label>
                                </div>
                            </li>
                            <li class="col-xs-3">
                                <div class="input-group">
                                    <div class="input-group-addon"><input type="checkbox" id="fl_kipem_sudah_habis" name="fl_kipem_sudah_habis" class="input-sm"></div>
                                    <label for="fl_kipem_sudah_habis" class="form-control label-filter input-sm">Kipem sudah habis</label>
                                </div>
                            </li>
                            <li class="sc-button">
                                <button class="btn btn-primary btn-sm" type="submit"><i class="fa fa-search"></i> Cari</a></button>
                            </li>
                        </ul>
                        </form>
                        <div class="collapse-toggle"><a href="#" id="sc-collapse" class="info-tooltip" data-original-title="Toggle Search Collapse"><i class="fa fa-angle-double-up"></i></a></div>
                    </div>
                </div>
                <div class="row">
                    <div id="box-result" class="col-md-12">

                        <div id="map_canvas"></div>
                        <input type="hidden" id="latFld" value="{{ isset($lingkungan['lat_lng'][0]) ? $lingkungan['lat_lng'][0] : '-8.65000';  }}">
                        <input type="hidden" id="lngFld" value="{{ isset($lingkungan['lat_lng'][1]) ? $lingkungan['lat_lng'][1] : '115.21667';  }}">

                    </div>
                </div>
            </div><!-- /.box-body -->
        </div><!-- /.box -->
    </div>
</div>

@include('lokasis.partials.create-modal')

@stop

@section('javascript')
<script type="text/javascript">
    // global vars
    var add_marker    = false;
    var map;
    var markersArray  = [];
    var polygonCoords = [];
    var infowindow    = null;

    // filtering needs
    var fl_nama_lokasi = "";
    var fl_tipe        = "";
    var fl_kipem       = "";

    // Deletes all markers in the array by removing references to them
    function deleteOverlays() {
        if (markersArray) {
            for (i in markersArray) {
                markersArray[i].setMap(null);
            }
            markersArray.length = 0;
        }
    }

    function placeMarker(lokasis) {
        deleteOverlays();

        lokasis.forEach(function(lokasi){

            // var marker = new MarkerWithLabel({
            //     position: new google.maps.LatLng(lokasi.lat_lng[0], lokasi.lat_lng[1]),
            //     draggable: false,
            //     map: map,
            //     labelContent: lokasi.nama,
            //     labelAnchor: new google.maps.Point(0, 0),
            //     labelClass: "label label-primary label-googlemap", // the CSS class for the label
            //     labelStyle: {opacity: 0.75}
            // });

            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(lokasi.lat_lng[0], lokasi.lat_lng[1]),
                draggable: false,
                map: map
            });

            // add marker in markers array
            markersArray.push(marker);
            console.log(marker);

            google.maps.event.addListener(marker, 'click', function () {
                var current = this;
                var promise = $.ajax({
                    url: "{{ URL::route('lokasis.get.marker.infowindow') }}",
                    type: 'get',
                    data: {
                        id: lokasi.id
                    }
                });

                promise.done(function(data){
                    infowindow.setContent(data);
                    infowindow.open(map, current);
                });
            });
        });
    }

    function initialize_map_popover(id_map, lat_lng) {
        var lat_lng = lat_lng.split('|');

        var map_canvas = document.getElementById(id_map);
        var map_options = {
            center: new google.maps.LatLng( {{ $lingkungan['lat_lng'][0] }}, {{ $lingkungan['lat_lng'][1] }} ),
            zoom: {{ isset($lingkungan['zoom']) ? $lingkungan['zoom'] : '18';  }},
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var map = new google.maps.Map(map_canvas, map_options);

        // get polygon data
        var promise = $.getJSON("{{ URL::route('lingkungan.get.polygon.json') }}");
        promise.done(function(coordinates){
            for (var key in coordinates) {
                var lat_lng = coordinates[key];
                polygonCoords.push(new google.maps.LatLng(lat_lng.lat, lat_lng.lng));
            }

            if(polygonCoords.length > 0) {
                var polygon = new google.maps.Polygon({
                    paths: polygonCoords
                });
                polygon.setMap(map);
            }
        });

        // Add marker
        var location = new google.maps.LatLng(lat_lng[0], lat_lng[1]);
        map.setCenter(new google.maps.LatLng(lat_lng[0], lat_lng[1]));

        var marker = new google.maps.Marker({
            position: location,
            draggable: true,
            map: map
        });

        google.maps.event.addListener(marker, 'dragend', function()
        {
            $('#latFld').val( marker.getPosition().d );
            $('#lngFld').val( marker.getPosition().e );
        });
    }

	$(document).ready(function() {

        function initialize() {
            // initialize google map
            var lat = $('#latFld').val();
            var lng = $('#lngFld').val();
            var map_canvas = document.getElementById('map_canvas');
            var map_options = {
                center: new google.maps.LatLng(lat, lng),
                zoom: {{ isset($lingkungan['zoom']) ? $lingkungan['zoom'] : '18';  }},
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            map = new google.maps.Map(map_canvas, map_options);

            infowindow = new google.maps.InfoWindow({
                content: "<div class='text-center'><i class='fa fa-repeat fa-spin fa-2x'></i></div>"
            });

            // get polygon data
            var promise = $.getJSON("{{ URL::route('lingkungan.get.polygon.json') }}");
            promise.done(function(coordinates){
                for (var key in coordinates) {
                    var lat_lng = coordinates[key];
                    polygonCoords.push(new google.maps.LatLng(lat_lng.lat, lat_lng.lng));
                }

                if(polygonCoords.length > 0) {
                    var polygon = new google.maps.Polygon({
                        paths: polygonCoords
                    });
                    polygon.setMap(map);
                }
            });

            // get marker data
            var promise = $.getJSON("{{ URL::route('lokasis.get.all.markers') }}");
            promise.done(function(lokasis){
                placeMarker(lokasis);
            });

            // add a click event handler to the map object
            google.maps.event.addListener(map, "click", function(event)
            {
                if(add_marker) {
                    // place a marker
                    var new_marker = new google.maps.Marker({
                        position: event.latLng,
                        draggable: true,
                        map: map
                    });

                    google.maps.event.addListener(new_marker, 'dragend', function()
                    {
                        // show modal
                        $('#tambah-lokasi-modal').show('modal');
                    });
                }
            });
        }

        google.maps.event.addDomListener(window, 'load', initialize);

        $('#frmFilter').on('submit', function(event) {
            event.preventDefault();

            // Ajax request based on filter value
            var promise = $.ajax({
                url: "{{ URL::route('lokasis.get.all.markers') }}",
                type: 'get',
                data: $(this).serialize()
            });

            promise.done(function(lokasis) {
               placeMarker(lokasis);
            });
        });

        $(document).on('click', '.btn-detail', function(event) {
            event.preventDefault();

            var url = $(this).attr('href');
            global_lat_lng = $(this).data('lat_lng');

            $('#detail-lokasi-modal').modal('show');
            showLoader($('#detail-lokasi-modal').find('.modal-body'));

            var promise = $.ajax({
                url: url,
                type: 'get'
            });
            promise.done(function(data){
                $('#detail-lokasi-modal').find('.modal-body').html(data);
            });
        });

        /**
         * On modal detail shown load the initalize google map
         */
        $('#detail-lokasi-modal').on('shown.bs.modal', function (e) {
            initialize_map_popover('mapModal', global_lat_lng);
        });

        $('.btn-tambah-lokasi').on('click', function(event) {
            event.preventDefault();

            var notice = new PNotify({
                text: "Klik lokasi dipeta untuk lokasi yang baru",
                type: "info",
                shadow: false,
                opacity: .8
            });

            add_marker = true;
        });
	});
</script>
@stop
